package clickhouse

import (
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"time"

	"gorm.io/driver/clickhouse"
)

func New(c Conf) (*gorm.DB, error) {
	var dialector gorm.Dialector
	dialector = clickhouse.Open(c.DSN())

	gconfig := &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   c.TablePrefix,
			SingularTable: true,
		},
	}

	db, err := gorm.Open(dialector, gconfig)
	if err != nil {
		return nil, err
	}

	if c.Debug {
		db = db.Debug()
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}

	// 设置连接数
	maxIdleConns := 50
	maxOpenConns := 150
	maxLifetime := 7200
	if c.MaxIdleConns > 0 {
		maxIdleConns = c.MaxIdleConns
	}
	if c.MaxOpenConns > 0 {
		maxOpenConns = c.MaxOpenConns
	}

	if c.MaxLifetime > 0 {
		maxLifetime = c.MaxLifetime
	}

	sqlDB.SetMaxIdleConns(maxIdleConns)
	sqlDB.SetMaxOpenConns(maxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Duration(maxLifetime) * time.Second)

	return db, nil
}
